package leecode

func islandPerimeter(grid [][]int) int {
	var dfs func(grid [][]int, row, column int) int
	dfs = func(grid [][]int, row, column int) int {
		if !isArea463(grid, row, column) {
			//如果超过边界 , 返回一条边
			return 1
		}
		if grid[row][column] == 0 {
			//如果是海洋
			return 1
		}
		if grid[row][column] == 2 {
			//已经遍历过的格子 , 不再使用
			return 0
		}
		grid[row][column] = 2
		//上
		top := dfs(grid, row-1, column)
		//下
		down := dfs(grid, row+1, column)
		//左
		left := dfs(grid, row, column-1)
		//右
		right := dfs(grid, row, column+1)
		return top + down + left + right
	}
	for i := 0; i < len(grid); i++ {
		for j := 0; j < len(grid[i]); j++ {
			if grid[i][j] == 1 {
				return dfs(grid, i, j)
			}
		}
	}
	return 0
}

func isArea463(grid [][]int, row, column int) bool {
	return 0 <= row && row < len(grid) && 0 <= column && column < len(grid[0])
}
